import {
  HttpException,
  HttpStatus,
  Injectable,
  ServiceUnavailableException,
} from '@nestjs/common';
import { Repository } from 'typeorm';
import { CreateGoodsDto } from '../dto/goods/create-goods.dto';
import { UpdateGoodsDto } from '../dto/goods/update-goods.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Goods } from '../entities/goods.entity';
import { ResMsg } from 'src/utils/public.enum';
import { ListGoodsDto } from '../dto/goods/list-goods.dto';

@Injectable()
export class GoodsService {
  constructor(
    @InjectRepository(Goods, 'shop')
    private readonly goodsRepository: Repository<Goods>,
  ) {}

  async create(createGoodsDto: CreateGoodsDto) {
    try {
      const row = new Goods(createGoodsDto);
      const result = await this.goodsRepository.save(row);

      if (result) {
        return ResMsg.Success;
      }
      return ResMsg.Fail;
    } catch (e) {
      throw new ServiceUnavailableException(e);
    }
  }

  async findAll(listGoodsDto: ListGoodsDto) {
    try {
      const {
        id = null,
        title = '',
        desc = '',
        categoryId = null,
      } = listGoodsDto.queryDto;
      const queryBuilder = this.goodsRepository.createQueryBuilder('goods');

      if (id) {
        queryBuilder.where('goods.id = :id', { id });
      }

      if (categoryId) {
        queryBuilder.andWhere('goods.category_id = :categoryId', { categoryId });
      }

      queryBuilder
        .andWhere('goods.is_delete = :isDelete', { isDelete: 1 })
        .andWhere('goods.title LIKE :title AND goods.desc LIKE :desc', {
          title: `%${title}%`,
          desc: `%${desc}%`,
        });

      const [list, total] = await queryBuilder
        .orderBy('goods.modify_time', 'DESC')
        .skip((listGoodsDto.pageDto.pageNo - 1) * listGoodsDto.pageDto.pageSize)
        .take(listGoodsDto.pageDto.pageSize)
        .getManyAndCount();

      return {
        list,
        total,
        ...listGoodsDto.pageDto,
      };
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async findOne(id: number): Promise<Goods> {
    try {
      const res = await this.goodsRepository.findOneBy({
        id,
        isDelete: 1,
      });
      return res;
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async update(id: number, updateGoodsDto: UpdateGoodsDto) {
    try {
      const dbRow = await this.findOne(id);
      if (dbRow) {
        const data = {
          ...dbRow,
          ...updateGoodsDto,
        };
        const result = this.goodsRepository.save(data);
        if (result) {
          return ResMsg.Success;
        }
        return ResMsg.Fail;
      } else {
        throw new HttpException('当前数据不存在！', HttpStatus.BAD_REQUEST);
      }
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async remove(id: number) {
    try {
      const dbRow = await this.findOne(id);
      if (dbRow) {
        const data = {
          ...dbRow,
          isDelete: -1,
        };
        const result = this.goodsRepository.save(data);
        if (result) {
          return ResMsg.Success;
        }
        return ResMsg.Fail;
      } else {
        throw new HttpException('当前数据不存在！', HttpStatus.BAD_REQUEST);
      }
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }
}
